package org.az.netty_study.p16_rpc.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.az.netty_study.p16_rpc.message.RpcResMessage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResMessage> {

    public static final Map<Integer, Promise<Object>> map = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResMessage msg) throws Exception {
        //将返回结果放进Promise
        Promise<Object> promise = map.get(msg.getSequenceId());
        if (promise != null) {
            String e = msg.getExceptionValue();
            if (e != null) {
                promise.setFailure(new Exception(e));
            } else {
                promise.setSuccess(msg.getReturnValue());
            }

        }
        log.info("{}", msg);
    }
}
